package com.Beans.Dao;

import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.Beans.Models.Empleado;
import com.Beans.Models.Solicitud;
import com.Beans.Dao.HibernateUtil;

public class SolicitudDAO {

	public static void persistSolicitud(Solicitud s){
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.persist(s);
			tr.commit();
		}catch(HibernateException e){
			tr.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
	}
	
	public static Solicitud findById(int id_solicitud){
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tr = null;
		Solicitud solicitud = null;
		try{
			tr = session.beginTransaction();
			Query q = session.createQuery("FROM Solicitud s WHERE s.idSolicitud = :id_solicitud");
			q.setParameter("id_solicitud", id_solicitud);
			solicitud = (Solicitud)q.uniqueResult();
			tr.commit();
		}catch(HibernateException e){
			tr.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
		return solicitud;
	}
	
	public static List<Solicitud> findByEmployee(Empleado empleado){
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tr = null;
		List <Solicitud> solicitudes = null;
		try{
			tr = session.beginTransaction();
			Query q = session.createQuery("FROM Solicitud s WHERE s.empleado = :empleado ORDER BY s.fechaEmision DESC");
			q.setParameter("empleado", empleado);
			solicitudes = (List<Solicitud>)q.list();
			tr.commit();
		}catch(HibernateException e){
			tr.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
		return solicitudes;
	}
	
	public static List<Solicitud> findByArea(int area_id){
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tr = null;
		List <Solicitud> solicitudes = null;
		try{
			tr = session.beginTransaction();
			Query q = session.createQuery("FROM Solicitud s WHERE s.idAreaDestino = :area_id ORDER BY s.fechaEmision DESC");
			q.setParameter("area_id", area_id);
			solicitudes = (List<Solicitud>)q.list();
			tr.commit();
		}catch(HibernateException e){
			tr.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
		return solicitudes;
	}
	
	public static void update(Solicitud solicitud){
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tr =null;
		try{
			tr = session.beginTransaction();
			session.update(solicitud);
			tr.commit();
		}catch(HibernateException e){
			tr.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
	}
}
